package com.kede.config;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Objects;

/***
 ** @Author:Pr.li
 ** @Description:
 ** @Date: create in 2023/5/27 17:42
 ***/
public class NullValueSerializer extends JsonSerializer<Object> {
    @Override
    public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        String fieldName = jsonGenerator.getOutputContext().getCurrentName();
        //反射获取字段
        Field field = ReflectUtil.getField(jsonGenerator.getCurrentValue().getClass(), fieldName);
        if (ObjectUtil.isNotNull(field)){
            // 数字类型Integer、Double、Long等返回null
            if (Number.class.isAssignableFrom(field.getType())){
                jsonGenerator.writeNull();
                return;
            }
            //String类型返回""
            if (Objects.equals(field.getType(), String.class)) {
                jsonGenerator.writeString("");
                return;
            }
            //List类型返回[]
            if (Objects.equals(field.getType(), List.class)) {
                jsonGenerator.writeStartArray();
                jsonGenerator.writeEndArray();
                return;
            }
            //其他Object默认返回{}
            jsonGenerator.writeStartObject();
            jsonGenerator.writeEndObject();
        }
    }
}
